package com.luck.easyfoodbatch.ui;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.Constant;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.fragment.FragmentShopMoreViewPager;
import com.luck.easyfoodbatch.fragment.ShopDetailsFragment;
import com.luck.easyfoodbatch.mvp.mine.CollectModel;
import com.luck.easyfoodbatch.mvp.mine.CollectPresenter;
import com.luck.easyfoodbatch.mvp.mine.CollectView;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.GoodModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.verticalslide.DragLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopDetailsActivity extends BaseNoSliderActivity implements CollectView,ShopDetailsFragment.CallBackValue ,ShopDetailsFragment.CollectBackValue{

    @BindView(R.id.first)
    FrameLayout first;
    @BindView(R.id.second)
    FrameLayout second;
    @BindView(R.id.draglayout)
    DragLayout draglayout;
    @BindView(R.id.left_back)
    ImageView leftBack;
    @BindView(R.id.btn_chat)
    Button btnChat;
    @BindView(R.id.btn_shopping)
    Button btnShopping;
    @BindView(R.id.ll_collection)
    LinearLayout ll_collection;
    @BindView(R.id.iv_collection)
    ImageView iv_collection;
    @BindView(R.id.tv_collection)
    TextView tv_collection;
    @BindView(R.id.btn_purchase)
    Button btnPurchase;
    @BindView(R.id.iv_cart)
    ImageView iv_cart;
    @BindView(R.id.iv_more)
    ImageView iv_more;
    private ShopDetailsFragment topFragment = new ShopDetailsFragment();
    private FragmentShopMoreViewPager moreViewPager =new FragmentShopMoreViewPager();
    private Handler handler = new Handler();
    private String gid = "", p_id = "";
    private static final int MSG_ACTION_CCALLBACK = 2;
    private String share_title = "易食批", share_url = "";
    private String share_text = "";
    private CollectModel collectModel;
    private int is_collect = 0;
    private GoodModel.DataBean data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_details);
        App.getInstance().addActivity(ShopDetailsActivity.this);
        ButterKnife.bind(this);
        gid = getIntent().getStringExtra("gid");
        p_id = (String) SharedPreferencesUtil.getData(ShopDetailsActivity.this, HttpUtil.P_ID, "3");
        share_url = "http://yishipi.com.cn/yspShare/goodsShare.html?gid=" + gid + "&sid=" + p_id;

        getSupportFragmentManager().beginTransaction()
                .add(R.id.first, topFragment)
                .commit();


        DragLayout.ShowNextPageNotifier nextFragment = new DragLayout.ShowNextPageNotifier() {
            @Override
            public void onDragNext() {
                // 初始化下一页面
            }
        };

        /**
         * 延迟1秒加载下一页 防止卡顿
         */
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    getSupportFragmentManager().beginTransaction().add(R.id.second, moreViewPager)
                            .commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, 1000);
        draglayout = (DragLayout) findViewById(R.id.draglayout);
        draglayout.setNextPageListener(nextFragment);
    }

    @OnClick({R.id.left_back, R.id.btn_chat, R.id.btn_shopping, R.id.btn_purchase, R.id.iv_cart, R.id.iv_more,R.id.ll_collection})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.left_back:
                finish();
                break;
            case R.id.btn_chat:
                if (Onrecord()) {
                    if (isCheckedLogin()) {
                        if (topFragment != null) {
                            bundle.putString(Constant.EXTRA_USER_ID, topFragment.getToChatUserName());
                            bundle.putString(Constant.EXTRA_NICK_ID, topFragment.getNickName());
                            startAct(ChatActivity.class, bundle);
                        }
                    } else {
                        startAct(LoginActivity.class);
                    }
                }
                break;
            case R.id.iv_cart:
                if (!isCheckedLogin()) {
                    startAct(LoginActivity.class);
                } else {
                    sendBroadcast("action.app.cart");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(800);
                                App.getInstance().exitbefore();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
                break;
            case R.id.btn_shopping:
                if (isCheckedLogin()) {
                    if (topFragment != null) {
                        topFragment.onActivityClick(1);
                    }
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.btn_purchase:
                if (isCheckedLogin()) {
                    if (topFragment != null) {
                        topFragment.onActivityClick(2);
                    }
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.iv_more:
                new PopupWindows(mContext, view);
                break;
            case R.id.ll_collection:
                // 收藏
                if (isCheckedLogin()) {
                    showProgressDialog(getString(R.string.app_loading));
                    collectModel = new CollectPresenter(ShopDetailsActivity.this, mContext);
                    collectModel.collect("1", gid, p_id);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
        }
    }

    @Override
    public void SendMessageValue(String strValue) {
        share_text = strValue;
    }

    @Override
    public void SendMessageIsCollect(int isCollect) {
        is_collect=isCollect;
        switch (is_collect) {
            case 0:
                iv_collection.setImageResource(R.mipmap.addshoucang);
                tv_collection.setText("收藏");
                break;
            case 1:
                iv_collection.setImageResource(R.mipmap.addshoucangs);
                tv_collection.setText("已收藏");
                break;
        }
    }

    @Override
    public void collectSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                String msg = model.getMsg();
                if (!Tools.isNull(msg) && msg.equals("收藏成功")) {
                    iv_collection.setImageResource(R.mipmap.addshoucangs);
                    tv_collection.setText("已收藏");
                    if (this.data != null) {
                        this.data.setIs_collect("1");
                    }
                } else if (!Tools.isNull(msg) && msg.equals("取消成功")) {
                    iv_collection.setImageResource(R.mipmap.addshoucang);
                    tv_collection.setText("收藏");
                    if (this.data != null) {
                        this.data.setIs_collect("0");
                    }
                }
                T.showToast(mContext, msg);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    /**
     * 更多
     */
    public class PopupWindows extends PopupWindow {

        public PopupWindows(final Context mContext, View parent) {
            super(mContext);
            View view = View.inflate(mContext, R.layout.shop_details_more, null);
            LinearLayout ll_message = (LinearLayout) view.findViewById(R.id.ll_message);
            LinearLayout ll_home = (LinearLayout) view.findViewById(R.id.ll_home);
            setWidth(App.screenWidth / 4);
            setAnimationStyle(R.style.PopupAnimation);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAsDropDown(parent);
            update();
            ll_message.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isCheckedLogin()) {
                        startAct(MessageActivity.class);
                    } else {
                        startAct(LoginActivity.class);
                    }
                    dismiss();
                }
            });
            ll_home.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sendBroadcast("action.app.main");
                    setResult(RESULT_OK);
                    App.getInstance().exitbefore();
                }
            });
        }
    }


    /**
     * @author lmw
     * @ClassName: PopupWindows
     * @Description: 分享PopupWindow
     * @date 2015年3月30日 上午9:30:41
     */
    /**
     * 关闭 PopupWindows
     *
     * @param view
     * @param popupWindow
     */
    private void hidePopupWindows(View view, final PopupWindow popupWindow) {
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.pophidden_anim);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                popupWindow.dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(animation);
    }

    //录音电话权限管理
    //final public static int REQUEST_CODE_ASK_RECORD_AUDIO = 131;

    public boolean Onrecord() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ShopDetailsActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
                //Tools.callPhone(mobile,mContext);
                return false;
            } else {
                return true;
                //Tools.callPhone(mobile,mContext);
            }
        } else {
            return true;
            // Tools.callPhone(mobile,mContext);
        }
    }
}
